package com.bby.user.manager;

import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.nio.charset.StandardCharsets;

@Component//单例设计模式
public class TokenManager {
    private JedisPool jedisPool;

    @Value(value = "${settings.cookie_alive_second}")
    long cookie_alive_second;
    public TokenManager(JedisPool jedisPool) {
        this.jedisPool=jedisPool;
    }

    /**
     * 根据token获取已经连接的用户id，失效则返回空
     * @param token
     * @return: userId
     * @author: 本小蛋
     * @time: 2021/8/16 11:28
     */
    public String readUserId (String token){
        if (ObjectUtils.isEmpty(token)) return "";
        try (Jedis jedis = jedisPool.getResource()){
            String userId = jedis.get(token);
            if (userId!=null){
//                jedis.expire(token,cookie_alive_second);
                return userId;
            }else jedis.del(token);
        }catch (Exception e){
        }
        return "";
    }
    /**
     * 添加一个登陆状态记录
     * @param userId 用户 id
     * @return: token
     * @author: 本小蛋
     * @time: 2021/8/16 12:09
     */
    public String addLoginState(String userId,long alive_second){
        HMac mac =new HMac(HmacAlgorithm.HmacMD5, userId.getBytes(StandardCharsets.UTF_8));
        String token = mac.digestHex(((int)(Math.random()*1000000)+userId));
        try (Jedis jedis =jedisPool.getResource()){
            jedis.set(token,userId,new SetParams().ex(alive_second));
            return token;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }
    public boolean delLoginState(String token){
        try (Jedis jedis =jedisPool.getResource()){
            return jedis.del(token)==1;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
